import requests
import json
headers = {
    'Content-Type': 'application/json' 
}
def stream_post_response(url, data=None):
    # 发送POST请求并启用流式接收
    response = requests.post(url, json=data, headers=headers,stream=True)
    # 检查响应状态码
    if response.status_code == 200:
        # 逐行读取流式响应
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:  # 过滤空块
                # 处理每个数据块
                try:
                    decoded_chunk = chunk.decode('utf-8')
                    yield decoded_chunk
                except UnicodeDecodeError:
                    # 尝试其他编码方式或跳过无效数据
                    try:
                        decoded_chunk = chunk.decode('utf-8', errors='ignore')
                        yield decoded_chunk
                    except:
                        yield "[解码错误: 跳过无效数据]"
                except Exception as e:
                    yield f"[处理错误: {str(e)}]"
    else:
        yield f"Error: {response.status_code} - {response.text}"

if __name__ == "__main__":
    # 示例使用
    url = 'http://ai.yelob.vip/ai'
    data = {"prompt": "密hhh的"}
    # stream_post_response(url, data=data)
    for chunk in stream_post_response(url, data=data):
        print(chunk)